import time, os, sys, network, socket, ustruct, json
from media.vencoder import *
from media.sensor import *
from media.display import *
from media.media import *
import uctypes

class CameraStreamer:
    _DEFAULT_CONFIG = {
            "ip": "0.0.0.0",
            "port": 6001,
            "ssid": "K230-Camera",
            "key": "12345678",  # 修改为key而不是pwd
            "w": 640,  # 降低默认分辨率
            "h": 360,  # 降低默认分辨率
            "chn": CAM_CHN_ID_2,  # 确保使用CAM_CHN_ID_2通道
            "chunk_size": 8192,  # 减小数据块，提高传输稳定性
            "timeout": 15,
            "tcp_reconnect": 500,
            "mode": "websocket"  # 新增模式: "tcp" 或 "websocket"
    }
    sock = None
    streamData = StreamData()
    tcp_connect_t = time.ticks_ms()
    tcp_connect = False
    clients = []  # WebSocket客户端列表
    
    def __init__(self, ip="0.0.0.0", port=6001, ssid="K230-Camera", pwd="12345678", w=640, h=360, sensor=None, mode="websocket", debug=False):
        # 导入垃圾回收器，避免内存问题
        import gc
        gc.collect()
        
        self.cfg = CameraStreamer._DEFAULT_CONFIG.copy()

        self.cfg["ip"] = ip
        self.cfg["port"] = port
        self.cfg["ssid"] = ssid
        self.cfg["key"] = pwd  # 保持兼容性，但内部使用key
        self.cfg["w"] = w
        self.cfg["h"] = h
        self.cfg["mode"] = mode
        self.clients = []  # WebSocket客户端列表
        self.debug = debug  # 是否输出调试信息

        # 初始化编码器
        self.encoder = Encoder()
        
        # 配置H265编码参数
        if self.debug:
            print("[调试] 配置H.265编码器: " + str(self.cfg["w"]) + "x" + str(self.cfg["h"]))
        try:
            self.encoder.SetOutBufs(chn=VENC_CHN_ID_0, buf_num=8, width=self.cfg["w"], height=self.cfg["h"])
            self.chnAttr = ChnAttrStr(
                self.encoder.PAYLOAD_TYPE_H265,
                self.encoder.H265_PROFILE_MAIN,
                self.cfg["w"],
                self.cfg["h"]
            )
            if self.debug:
                print("[调试] H.265编码器配置成功")
        except Exception as e:
            print("[错误] H.265编码器配置失败: " + str(e))
            # 尝试释放一些内存
            gc.collect()
            
        # 配置传感器通道
        if sensor:
            # 确保在设置之前先打印和检查参数
            print("[调试] 为传感器设置分辨率: " + str(self.cfg["w"]) + "x" + str(self.cfg["h"]))
            try:
                # 不再重复设置传感器参数，避免冲突
                print("[调试] 使用main.py中已配置的传感器通道")
                self.sensor = sensor  # 保存sensor引用用于后续处理
                print("[调试] 传感器通道配置成功")
            except Exception as e:
                print("[错误] 传感器配置失败: " + str(e))
                self.sensor = None
        else:
            self.sensor = None

    def start(self):
        print("[调试] 启动CameraStreamer...")
        # 导入垃圾回收器，避免内存问题
        import gc
        gc.collect()
        
        if self.cfg["mode"] == "tcp":
            # 传统TCP模式，需要连接到WiFi
            if not self.connect_wifi():
                return
        # AP模式下不需要连接WiFi，因为K230自己就是AP
        
        # 启动编码器
        print("[调试] 创建H265编码器...")
        try:
            print("[调试] 准备创建编码器通道...")
            self.encoder.Create(VENC_CHN_ID_0, self.chnAttr)
            print("[调试] 启动H265编码器...")
            self.encoder.Start(VENC_CHN_ID_0)
            print("[调试] H265编码器启动成功")
        except Exception as e:
            print("[错误] H265编码器启动失败: " + str(e))
            # 尝试清理内存并重试
            try:
                print("[调试] 尝试清理内存并重试...")
                gc.collect()
                self.encoder.Create(VENC_CHN_ID_0, self.chnAttr)
                self.encoder.Start(VENC_CHN_ID_0)
                print("[调试] 第二次尝试成功")
            except Exception as e2:
                print("[错误] 第二次尝试也失败: " + str(e2))
                return
        
        # 创建媒体链接(需要在sensor.run()之后创建)
        print("[调试] 检查传感器状态...")
        if hasattr(self, 'sensor') and self.sensor:
            # 确保传感器已经运行
            if not hasattr(self.sensor, 'is_running'):
                print("[警告] 无法确认传感器是否正在运行，尝试继续...")
            
            try:
                # 创建媒体链接
                print("[调试] 获取传感器绑定信息...")
                src_info = self.sensor.bind_info(chn=self.cfg["chn"])
                print("[调试] 传感器绑定信息: " + str(src_info))
                
                print("[调试] 创建媒体链接...")
                link = MediaManager.link(
                    src_info['src'],
                    (VIDEO_ENCODE_MOD_ID, VENC_DEV_ID, VENC_CHN_ID_0)
                )
                print("[调试] 媒体链接创建成功")
            except Exception as e:
                print("[错误] 媒体链接创建失败: " + str(e))
                print("[警告] 尝试继续执行，但视频流可能无法正常工作")
        else:
            print("[警告] 没有可用的传感器，跳过媒体链接创建")
        
        # 启动服务器
        if self.cfg["mode"] == "websocket":
            print("[调试] 选择WebSocket服务器模式")
            self.start_websocket_server()
        else:
            print("[调试] 选择TCP客户端模式")
            # TCP模式下，作为客户端连接到服务器
            self.tcp_connect = self.connect_tcp()
        
        print("[调试] CameraStreamer启动完成")

    def deint(self):
        print("[调试] 关闭CameraStreamer资源...")
        # 关闭编码器
        try:
            print("[调试] 停止编码器...")
            self.encoder.Stop(VENC_CHN_ID_0)
            print("[调试] 销毁编码器...")
            self.encoder.Destroy(VENC_CHN_ID_0)
        except Exception as e:
            print("[警告] 关闭编码器时出错: " + str(e))
        
        # 关闭网络连接
        if self.cfg["mode"] == "tcp":
            self.close_tcp()
        else:
            self.close_websocket_server()
        
        # 清理内存
        try:
            import gc
            gc.collect()
        except:
            pass
        
        print("[调试] CameraStreamer资源清理完成")

    def check(self):
        """检查并处理视频流"""
        try:
            if self.cfg["mode"] == "tcp":
                # TCP客户端模式
                if not self.tcp_connect:
                    if time.ticks_diff(time.ticks_ms(), self.tcp_connect_t) > self.cfg["tcp_reconnect"]:
                        self.tcp_connect_t = time.ticks_ms()
                        self.tcp_connect = self.connect_tcp()
                    else:
                        return
                
                # 获取编码流
                try:
                    # 添加错误处理和重试机制
                    try:
                        self.encoder.GetStream(VENC_CHN_ID_0, self.streamData)
                        if not self.send_h265_frame(self.streamData):
                            self.close_tcp()
                        self.encoder.ReleaseStream(VENC_CHN_ID_0, self.streamData)
                    except Exception as e:
                        if "timeout" in str(e).lower():
                            # 超时错误，可能是编码器暂时没有数据
                            if self.debug:
                                print("[警告] 获取编码流超时，等待下一帧")
                        else:
                            # 其他错误需要报告
                            print("[错误] 获取/发送TCP流失败: " + str(e))
                            self.close_tcp()
                except Exception as e:
                    print("[错误] 获取/发送TCP流失败: " + str(e))
                    self.close_tcp()
            else:
                # WebSocket服务器模式
                # 每5次check才检查一次新客户端
                if not hasattr(self, '_accept_counter'):
                    self._accept_counter = 0
                
                self._accept_counter += 1
                if self._accept_counter >= 5:
                    self._accept_counter = 0
                    try:
                        # 设置更短的超时时间，减少阻塞
                        self.accept_new_clients(100)  # 缩短超时时间到100ms
                    except Exception as e:
                        # 只在调试模式下打印错误
                        if hasattr(self, 'debug') and self.debug:
                            print("[错误] 接受新客户端连接失败: " + str(e))
                
                # 只有存在客户端时才尝试发送视频流
                client_count = len(self.clients)
                if client_count > 0:
                    try:
                        # 获取编码流，添加错误处理
                        try:
                            self.encoder.GetStream(VENC_CHN_ID_0, self.streamData)
                            # 检查数据是否有效
                            if self.streamData.pack_cnt > 0:
                                self.broadcast_h265_frame(self.streamData)
                            self.encoder.ReleaseStream(VENC_CHN_ID_0, self.streamData)
                        except Exception as e:
                            if "timeout" in str(e).lower():
                                # 超时错误，可能是编码器暂时没有数据
                                if self.debug:
                                    print("[警告] 获取编码流超时，等待下一帧")
                            else:
                                # 其他错误需要报告
                                if hasattr(self, 'debug') and self.debug:
                                    print("[错误] 获取/发送WebSocket流失败: " + str(e))
                    except Exception as e:
                        if hasattr(self, 'debug') and self.debug:
                            print("[错误] 获取/发送WebSocket流失败: " + str(e))
        except Exception as e:
            print("[错误] 检查流程序时出错: " + str(e))
            # 尝试清理内存
            try:
                import gc
                gc.collect()
            except:
                pass

    def connect_wifi(self):
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        if not wlan.isconnected():
            print("正在连接 " + self.cfg['ssid'] + "...")
            wlan.connect(self.cfg["ssid"], self.cfg["key"])  # 使用key而不是pwd
            start = time.ticks_ms()
            while not wlan.isconnected():
                if time.ticks_diff(time.ticks_ms(), start) > self.cfg["timeout"]*1000:
                    print("错误: WiFi连接超时")
                    return False
                time.sleep_ms(100)
        ip = wlan.ifconfig()[0]
        while ip == "0.0.0.0":
            ip = wlan.ifconfig()[0]
        print("WiFi已连接 IP:" + ip)
        return True

    def connect_tcp(self) -> bool:
        if self.sock:
            return True
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        addr = socket.getaddrinfo(self.cfg["ip"], self.cfg["port"])[0][-1]
        try:
            self.sock.connect(addr)
            print("已连接服务器 " + self.cfg['ip'] + ":" + str(self.cfg['port']))
            self.send_title()
            return True
        except Exception as e:
            print("连接失败: " + str(e))
            return False

    def close_tcp(self):
        if self.sock:
            self.sock.close()
            self.sock = None

    def send_title(self):
        config_header = ustruct.pack("<LLL", 0xFFFFFFFF, self.cfg["w"], self.cfg["h"])
        sent = 0
        while sent < 12:  # 修正为12字节
            sent += self.sock.send(config_header[sent:])
            os.exitpoint()

    def send_h265_frame(self, streamData):
        total_size = sum(4 + streamData.data_size[i] for i in range(streamData.pack_cnt))
        nalu_count = streamData.pack_cnt
        header = ustruct.pack("<LL", total_size, nalu_count)

        # 构建合并的数据缓冲区
        data_buffer = bytearray()
        for i in range(nalu_count):
            nalu_size = streamData.data_size[i]
            data_buffer += ustruct.pack("<L", nalu_size)
            nalu_data = uctypes.bytearray_at(streamData.data[i], nalu_size)
            data_buffer.extend(nalu_data)

        # 发送包头和合并数据
        self.sock.send(header)
        total_sent = 0
        while total_sent < len(data_buffer):
            sent = self.sock.send(data_buffer[total_sent:total_sent+self.cfg["chunk_size"]])
            if sent == 0:
                raise RuntimeError("连接中断")
                break
            total_sent += sent
        return True

    # WebSocket相关方法
    def start_websocket_server(self):
        """启动WebSocket服务器"""
        print("[调试] 开始创建WebSocket服务器...")
        try:
            print("[调试] 创建WebSocket服务器套接字...")
            try:
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                print("[调试] 套接字创建成功")
            except Exception as e:
                print("[错误] 创建套接字失败: " + str(e))
                return
                
            print("[调试] 设置套接字选项...")
            try:
                self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                print("[调试] 套接字选项设置成功")
            except Exception as e:
                print("[错误] 设置套接字选项失败: " + str(e))
                if self.sock:
                    self.sock.close()
                    self.sock = None
                return
            
            try:
                # 获取本地IP地址，用于确认绑定的正确性
                local_ip = "未知"
                if hasattr(network, "WLAN"):
                    if hasattr(network, "AP_IF"):
                        wlan = network.WLAN(network.AP_IF)
                        if wlan.active():
                            local_ip = wlan.ifconfig()[0]
                    elif hasattr(network, "STA_IF"):
                        wlan = network.WLAN(network.STA_IF)
                        if wlan.active() and wlan.isconnected():
                            local_ip = wlan.ifconfig()[0]
                
                # 绑定地址和端口
                server_address = (self.cfg["ip"], self.cfg["port"])
                print("[调试] 绑定WebSocket服务器到 " + self.cfg["ip"] + ":" + str(self.cfg["port"]))
                print("[调试] 本地IP地址: " + local_ip)
                
                try:
                    self.sock.bind(server_address)
                    print("[调试] 绑定成功")
                except Exception as e:
                    print("[错误] 绑定失败: " + str(e))
                    # 尝试使用本地IP地址绑定
                    if local_ip != "未知" and local_ip != "0.0.0.0":
                        try:
                            print("[调试] 尝试使用本地IP绑定: " + local_ip + ":" + str(self.cfg["port"]))
                            self.sock.bind((local_ip, self.cfg["port"]))
                            print("[调试] 使用本地IP绑定成功")
                        except Exception as e2:
                            print("[错误] 使用本地IP绑定也失败: " + str(e2))
                            if self.sock:
                                self.sock.close()
                                self.sock = None
                            return
                
                # 开始监听
                print("[调试] 设置监听...")
                try:
                    self.sock.listen(5)
                    print("[调试] 监听设置成功")
                except Exception as e:
                    print("[错误] 设置监听失败: " + str(e))
                    if self.sock:
                        self.sock.close()
                        self.sock = None
                    return
                
                print("[调试] WebSocket服务器启动成功，等待客户端连接...")
                
                # 设置非阻塞模式
                print("[调试] 设置非阻塞模式...")
                try:
                    self.sock.setblocking(False)
                    print("[调试] 非阻塞模式设置成功")
                except Exception as e:
                    print("[警告] 设置非阻塞模式失败: " + str(e))
                    print("[警告] 继续使用阻塞模式")
                
            except Exception as e:
                print("[错误] WebSocket服务器启动失败: " + str(e))
                self.close_websocket_server()
                
        except Exception as e:
            print("[错误] 创建WebSocket服务器失败: " + str(e))
            if hasattr(self, 'sock') and self.sock:
                self.sock.close()
                self.sock = None
            
        print("[调试] WebSocket服务器初始化完成")

    def close_websocket_server(self):
        """关闭WebSocket服务器"""
        # 关闭所有客户端连接
        for client in self.clients:
            try:
                client.close()
            except:
                pass
        self.clients = []
        
        # 关闭服务器套接字
        if self.sock:
            try:
                self.sock.close()
            except:
                pass
            self.sock = None

    def accept_new_clients(self, timeout=200):
        """接受新的WebSocket客户端连接
        timeout: 处理超时时间，单位毫秒
        """
        if not self.sock:
            return
        
        start_time = time.ticks_ms()
            
        try:
            # 非阻塞方式接受连接
            try:
                client_sock, client_addr = self.sock.accept()
                
                # 设置非阻塞模式
                client_sock.setblocking(False)
                
                # 处理WebSocket握手，设置短超时
                handshake_data = bytearray()
                handshake_start_time = time.ticks_ms()
                
                # 缩短握手等待时间
                while True:
                    # 检查超时
                    if time.ticks_diff(time.ticks_ms(), handshake_start_time) > timeout:
                        client_sock.close()
                        return
                        
                    try:
                        chunk = client_sock.recv(1024)
                        if not chunk:  # 连接已关闭
                            client_sock.close()
                            return
                            
                        handshake_data.extend(chunk)
                        
                        # 检查是否收到完整的握手请求
                        if b"\r\n\r\n" in handshake_data:
                            break  # 收到完整的握手请求
                    except OSError as e:
                        # 非阻塞模式下，没有数据可读会抛出异常
                        if e.args[0] == 11:  # EAGAIN
                            time.sleep_ms(5)  # 短暂休眠
                            continue
                        else:
                            client_sock.close()
                            return
                
                # 解析握手请求，提取Sec-WebSocket-Key
                key = None
                handshake_text = handshake_data.decode('utf-8', 'ignore')
                for line in handshake_text.split('\r\n'):
                    if line.startswith('Sec-WebSocket-Key:'):
                        key = line.split(':', 1)[1].strip()
                        break
                
                if not key:
                    client_sock.close()
                    return
                
                # 计算响应密钥
                try:
                    import uhashlib
                    import ubinascii
                    import base64
                    
                    magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
                    response_key = base64.b64encode(uhashlib.sha1(key.encode() + magic.encode()).digest())
                    
                    # 发送握手响应
                    response = (
                        b"HTTP/1.1 101 Switching Protocols\r\n"
                        b"Upgrade: websocket\r\n"
                        b"Connection: Upgrade\r\n"
                        b"Sec-WebSocket-Accept: " + response_key + b"\r\n\r\n"
                    )
                    client_sock.send(response)
                    
                    # 将客户端添加到列表
                    self.clients.append(client_sock)
                    
                    # 发送欢迎消息
                    welcome_msg = json.dumps({
                        "type": "info",
                        "message": "K230相机已连接",
                        "resolution": {
                            "width": self.cfg["w"],
                            "height": self.cfg["h"]
                        }
                    })
                    self.send_websocket_text(client_sock, welcome_msg)
                except:
                    client_sock.close()
                    return
            except OSError as e:
                # 非阻塞模式下，没有连接请求是正常的
                if e.args[0] != 11:  # EAGAIN
                    pass  # 忽略错误，继续执行
        except:
            pass  # 忽略所有异常，确保不阻塞主程序
            
        # 如果已经超过了半数超时时间，不进行客户端检查
        if time.ticks_diff(time.ticks_ms(), start_time) > timeout / 2:
            return
        
        # 限制检查已连接客户端的频率
        current_time = time.ticks_ms()
        if not hasattr(self, '_last_client_check_time') or time.ticks_diff(current_time, self._last_client_check_time) > 5000:
            self._last_client_check_time = current_time
            
            # 断开检测更简化，只检查是否可以读写
            active_clients = []
            for client in self.clients:
                try:
                    client.setblocking(False)
                    # 简单的连接测试
                    try:
                        # 尝试非阻塞接收，不期望有数据
                        client.recv(1)
                        active_clients.append(client)
                    except OSError as e:
                        # EAGAIN 表示没有数据但连接正常
                        if e.args[0] == 11:
                            active_clients.append(client)
                        else:
                            client.close()
                    except:
                        client.close()
                except:
                    # 任何错误都关闭连接
                    try:
                        client.close()
                    except:
                        pass
            
            # 更新活跃客户端列表
            self.clients = active_clients

    def send_websocket_binary(self, client, data):
        """发送WebSocket二进制数据"""
        try:
            # 计算数据大小
            data_size = len(data)
            
            # 检查数据大小，避免过大的数据包
            if data_size > 500 * 1024:  # 限制为500KB
                print("[警告] 数据包太大: " + str(data_size) + " 字节，将分片发送")
                # 分片发送
                chunk_size = 64 * 1024  # 64KB分片
                for i in range(0, data_size, chunk_size):
                    chunk = data[i:i+chunk_size]
                    self._send_websocket_frame(client, chunk, 0x02)  # 0x02表示二进制数据
                return
            
            # 发送完整的二进制帧
            self._send_websocket_frame(client, data, 0x02)  # 0x02表示二进制数据
            
        except Exception as e:
            print("[错误] 发送WebSocket二进制数据失败: " + str(e))
            # 移除失效的客户端
            if client in self.clients:
                self.clients.remove(client)
                try:
                    client.close()
                except:
                    pass

    def _send_websocket_frame(self, client, data, opcode=0x02):
        """发送WebSocket帧"""
        length = len(data)
        frame = bytearray()
        
        # 第一个字节: FIN位 + opcode
        frame.append(0x80 | opcode)  # 0x80表示FIN位为1，表示这是消息的最后一个帧
        
        # 第二个字节开始: 掩码位 + 长度
        if length < 126:
            frame.append(length)  # 不使用掩码
        elif length < 65536:
            frame.append(126)  # 使用16位长度
            frame.append((length >> 8) & 0xFF)
            frame.append(length & 0xFF)
        else:
            frame.append(127)  # 使用64位长度
            for i in range(7, -1, -1):
                frame.append((length >> (i * 8)) & 0xFF)
        
        # 添加数据
        if isinstance(data, bytearray):
            frame.extend(data)
        else:
            frame.extend(bytearray(data))
            
        # 发送帧
        client.send(frame)

    def send_websocket_text(self, client, text):
        """发送WebSocket文本数据"""
        try:
            # 将文本转换为字节数组
            data = text.encode('utf-8')
            
            # 发送文本帧
            self._send_websocket_frame(client, data, 0x01)  # 0x01表示文本数据
            
        except Exception as e:
            print("[错误] 发送WebSocket文本数据失败: " + str(e))
            # 移除失效的客户端
            if client in self.clients:
                self.clients.remove(client)
                try:
                    client.close()
                except:
                    pass

    def broadcast_h265_frame(self, streamData):
        """向所有WebSocket客户端广播H.265帧"""
        if not self.clients:
            return
            
        try:
            # 计算总数据大小
            total_size = 0
            for i in range(streamData.pack_cnt):
                total_size += 4 + streamData.data_size[i]
            nalu_count = streamData.pack_cnt
            
            # 构建帧头
            header = ustruct.pack("<LL", total_size, nalu_count)
            
            # 使用更高效的方式构建数据缓冲区
            try:
                # 预分配足够大小的缓冲区
                buffer_size = 8 + total_size  # 8字节头部 + 数据大小
                data_buffer = bytearray(buffer_size)
                
                # 复制头部
                for i in range(len(header)):
                    data_buffer[i] = header[i]
                
                # 当前位置
                pos = 8
                
                # 复制数据
                for i in range(nalu_count):
                    # 写入NAL单元大小
                    nalu_size = streamData.data_size[i]
                    size_bytes = ustruct.pack("<L", nalu_size)
                    for j in range(4):
                        data_buffer[pos + j] = size_bytes[j]
                    pos += 4
                    
                    # 复制NAL单元数据
                    nalu_data = uctypes.bytearray_at(streamData.data[i], nalu_size)
                    for j in range(nalu_size):
                        data_buffer[pos + j] = nalu_data[j]
                    pos += nalu_size
                
                # 处理客户端
                batch_size = 3  # 每次处理的客户端数量
                active_clients = []
                
                # 分批处理客户端
                for i in range(0, len(self.clients), batch_size):
                    batch = self.clients[i:i+batch_size]
                    for client in batch:
                        try:
                            self.send_websocket_binary(client, data_buffer)
                            active_clients.append(client)
                        except:
                            try:
                                client.close()
                            except:
                                pass
                
                # 更新活跃客户端列表
                self.clients = active_clients
                
            except Exception as e:
                print(f"[错误] 构建/发送数据缓冲区失败: {e}")
                # 尝试清理内存
                import gc
                gc.collect()
                
        except Exception as e:
            print("[错误] 广播H.265帧失败: " + str(e))
            # 尝试清理内存
            try:
                import gc
                gc.collect()
            except:
                pass

    def get_client_count(self):
        """获取当前连接的客户端数量"""
        if self.cfg["mode"] == "websocket":
            return len(self.clients)
        elif self.cfg["mode"] == "tcp":
            return 1 if self.tcp_connect else 0
        else:
            return 0

def camera_stream():
    # 配置媒体管理器 - 第一步
    print("[调试] 配置媒体管理器...")
    from media.media import k_vb_config, VB_REMAP_MODE_NOCACHE
    config = k_vb_config()
    config.max_pool_cnt = 1
    config.comm_pool[0].blk_size = 1024
    config.comm_pool[0].blk_cnt = 1
    config.comm_pool[0].mode = VB_REMAP_MODE_NOCACHE
    ret = MediaManager._config(config)
    if not ret:
        raise RuntimeError("缓冲区配置失败")
    print("[调试] 媒体管理器配置成功")
    
    # 初始化传感器
    print("[调试] 初始化传感器...")
    sensor = Sensor(id=2)
    sensor.reset()
    
    # 设置通道0用于显示
    print("[调试] 设置传感器分辨率...")
    sensor.set_framesize(width=640, height=480, chn=CAM_CHN_ID_0)
    sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_0)
    print("[调试] 传感器参数设置完成")
    
    # 创建CameraStreamer实例
    print("[调试] 创建CameraStreamer实例...")
    i = CameraStreamer(ip="0.0.0.0", port=6001, w=640, h=480, sensor=sensor, mode="websocket")
    
    # 初始化媒体管理器 - 在sensor.run()之前
    print("[调试] 初始化媒体管理器...")
    MediaManager.init()
    print("[调试] 媒体管理器初始化成功")
    
    # 启动传感器 - 不传递参数
    print("[调试] 启动传感器...")
    sensor.run()
    print("[调试] 传感器启动成功")
    
    # 启动CameraStreamer
    print("[调试] 启动CameraStreamer...")
    i.start()
    print("[调试] CameraStreamer启动成功")
    
    try:
        print("[调试] 进入主循环...")
        while 1:
            # 获取编码数据
            i.check()
            os.exitpoint()
    except Exception as e:
        print(f"主循环异常：{e}")
    finally:
        print("[调试] 清理资源...")
        try:
            sensor.stop()
            print("[调试] 传感器已停止")
        except Exception as e:
            print(f"[错误] 停止传感器失败: {e}")
        try:
            i.deint()
            print("[调试] CameraStreamer已释放")
        except Exception as e:
            print(f"[错误] 清理CameraStreamer失败: {e}")
        try:
            MediaManager.deinit()
            print("[调试] 媒体管理器已释放")
        except Exception as e:
            print(f"[错误] 清理媒体管理器失败: {e}")
        print("[调试] 程序结束")

if __name__ == "__main__":
    camera_stream()
